package com.maigao.core.login.dto;

import lombok.extern.slf4j.Slf4j;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Collection;

/**
 * @author awei
 * @description:
 * @date 2022/5/19 10:29 下午
 */
@Slf4j
public class BusinessObject {

    /**
     * (non-Javadoc)
     *
     * @see Object#toString()
     */
    @Override
    public String toString() {

        try {
            StringBuffer sb = new StringBuffer();
            sb.append("{");

            BeanInfo bi = Introspector.getBeanInfo(getClass(), Object.class);

            PropertyDescriptor[] pd = bi.getPropertyDescriptors();

            for (int i = 0; i < pd.length; i++) {
                if (pd[i].getPropertyType() != null && (!pd[i].getPropertyType().isArray())) {
                    try {
                        if (pd[i].getPropertyType().isPrimitive()) {
                            sb.append(pd[i].getName()).append("=").append(pd[i].getReadMethod().invoke(this)).append(";");
                        } else {
                            Object value = pd[i].getReadMethod().invoke(this);

                            if (null != value) {
                                if (value instanceof Collection<?>) {
                                    sb.append(pd[i].getName()).append("=").append("{");

                                    for (Object o : (Collection<?>) value) {
                                        sb.append("{").append(o).append("},");
                                    }

                                    sb.append("};");
                                } else {
                                    sb.append(pd[i].getName()).append("=").append(pd[i].getReadMethod().invoke(this)).append(";");
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("BusinessObject::toString()::", e);
                    }
                }
            }
            sb.append("}");
            return sb.toString();
        } catch (Exception e) {
            log.error("BusinessObject::toString()::", e);
        }

        return super.toString();
    }

    public String toString(String split) {
        return toString().replace(";", split);
    }
}